package middleware

import (
	jwt "github.com/e421083458/gin_scaffold/public"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type jwt_struct struct {
	Token string `json:"token"`
	Uid   int    `json:"uid"`
}

// Gin的中间件
func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}
		var message string
		code = 200

		//api := &dto.FindToken{}
		//if err := api.BindingValidParams(c); err != nil {
		//	ResponseError(c, 2001, err)
		//	return
		//}
		token := c.Request.Header.Get("token")
		if token == "" {
			code = 203
			message = "token不存在"
		} else {
			claims, err := jwt.ParseToken(token)
			if err != nil {
				code = 204
				message = err.Error()
			} else if time.Now().Unix() > claims.ExpiresAt {
				code = 205
				message = "token过期"
			}
			//else if claims.Uid != api.Uid {
			//	code = 206
			//	message = "用户uid不正确"
			//}
		}
		//
		if code != 200 {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  message,
				"data": data,
			})
			//
			c.Abort()
			return
		}
		c.Next()
	}
}
